package com.voja.salonschedule.data;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import com.voja.AndroidUtils.SQLiteHelper;
import com.voja.salonschedule.data.CustomerBalance.Balance;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

public class Customer extends AppModel {

	public String name="";
	
	public static class CustomerItem {
		public String name = "";
		public String phone = "";
		public byte[] image = new byte[]{};
		
		@Override
		public String toString() {
			return name;
		}
		
		public Bitmap bitmap() {
		    return getImageBitmap();
		}
		
		public Bitmap bitmap(int resourceId) {
		    Bitmap bm = getImageBitmap();
		    if (bm == null){
		        bm = BitmapFactory.decodeResource(context.getResources(), resourceId);
		    }
		    
		    return bm;
		}
		
		private Bitmap getImageBitmap() {
		    Bitmap bm = null;
            if (image != null && image.length > 0) {
                bm = BitmapFactory.decodeByteArray(image, 0, image.length);
            }
            return bm;
		}
		
		public void loadImageFromView(ImageView imageView) {
			Drawable d  = imageView.getDrawable();
			BitmapDrawable bmd = (BitmapDrawable)d;
			if (bmd != null) {
				Bitmap   bm = bmd.getBitmap();
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
				
				image = stream.toByteArray();
			}
		}
		
		public boolean hasPhone() {
			return phone != null && phone.length()>0;
		}
		
		public Balance getBalance() {
			CustomerBalance balance = new CustomerBalance(context);
			
			return balance.get(name);
		}
	};
	
	public Customer(Context c) {
		super(c);
	}
	
	public ArrayList<CustomerItem> getCustomers(String keyword) {
		ArrayList<CustomerItem> customers = new ArrayList<CustomerItem>();
		
		SQLiteHelper db = getConnection();
		db.open();
		
		if (keyword == null) {
		    keyword = "";
		}
		
		String sql = "SELECT name, image, phone FROM customers WHERE name LIKE '%"+keyword+"%' ORDER BY name";
		Cursor c = db.query(sql);
		CustomerItem customer;
		
		try {
    		while(c.moveToNext()) {
    			customer = new CustomerItem();
    			customer.name  = c.getString(0);
    			customer.image = c.getBlob(1);
    			customer.phone = c.getString(2);
    			customers.add(customer);
    		}
		} finally {
    		c.close();
    		db.close();
		}
		
		return customers;
	}
	
	public CustomerItem getCustomer(String name) {
		CustomerItem c = null;
		
		SQLiteHelper db = getConnection();
		db.open();
		
		String sql = "SELECT name, image, phone FROM customers WHERE name = " + escapeString(name);
		Cursor cur = db.query(sql);
		try {
    		while (cur.moveToNext()) {
    			c = new CustomerItem();
    			c.name  = cur.getString(0);
    			c.image = cur.getBlob(1);
    			c.phone = cur.getString(2);
    		}
		} finally {
		    cur.close();
		    db.close();
		}
		
		return c;
	}
	
	public boolean save(CustomerItem c) {
		boolean saved = true;
		
		if (getCustomer(c.name) != null) {
			return saved;
		}
		
		SQLiteHelper conn = getConnection();
		conn.open();
		
		
		ContentValues cv = new ContentValues();
		cv.put("name", c.name);
		cv.put("phone", c.phone);
		cv.put("image", c.image);
		
		SQLiteDatabase db = getDatabase();
		long id = db.insert("customers", "NULL", cv);
		if (id < 1) {
			saved = false;
		}
		conn.close();
		
		return saved;
	}
	
	public boolean update(CustomerItem c, String name) {
		boolean updated = true;
		
		SQLiteHelper conn = getConnection();
		conn.open();
		
		ContentValues cv = new ContentValues();
		cv.put("name", c.name);
		cv.put("phone", c.phone);
		cv.put("image", c.image);
		
		SQLiteDatabase db = getDatabase();
		
		// update the customer
		int ret = db.update("customers", cv, "name=" + escapeString(name), null);
		updated = ret>0;
		
		// update events
		if (c.name != name && updated) {
		    ContentValues ev = new ContentValues();
		    ev.put("customer", c.name);
		    db.update("events", ev, "customer=" + escapeString(name), null);
		}
		
		conn.close();
		return updated;
	}
	
	public boolean delete(String name) {
		boolean deleted = true;
		
		String sql = "DELETE FROM customers WHERE name='" + name + "'";
		SQLiteHelper db = getConnection();
		db.open();
		if (db.execute(sql) < 1) {
			deleted = false;
		}
		db.close();
		
		return deleted;
	}
	
	public boolean rename(String oldName, String newName) {
		boolean renamed = true;
		
		String sql = "UPDATE customers SET name='"+newName+"' WHERE name='"+oldName+"'";
		SQLiteHelper conn = getConnection();
		conn.open();
		if (conn.execute(sql) < 1) {
			renamed = false;
		}
		conn.close();
		
		return renamed;
	}
}
